﻿using HirelSeriesH.Entity;
using HirelSeriesH.Global;
using HirelSeriesH.Tools;
using MySql.Data.MySqlClient;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace HirelSeriesH
{
    class Initializer
    {
        static string[] ports;

        public static bool initializSystem(bool isInit)
        {
            try
            {
                InitializeDeviceToPort();
                InitializePower();
                InitializeEM();
                InitializeBox();
                InitializePLC();
                InitializeChannel(isInit);
                InitializeBasicData();
            }
            catch (Exception ex)
            {
                if (ex is FileNotFoundException)
                {
                    UIMessageDialog.ShowMessageDialog("Port.xml配置文件没有找到，系统启动失败，请联系系统管理员！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                }
                else
                {
                    UIMessageDialog.ShowMessageDialog("系统启动失败，异常类型：" + ex.GetType() + "，请联系系统管理员！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    Debug.WriteLine(ex.ToString());
                }
                return false;
            }
            return true;
        }

        /// <summary>
        /// 读取Port.xml文件，获取各个硬件与通信端口的对应关系。
        /// </summary>
        private static void InitializeDeviceToPort()
        {
            try
            {
                //配置文件路径
                string XmlFilePath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Port.xml";
                //初始化一个xml实例
                XmlDocument PortXmlDoc = new XmlDocument();
                //加载xml文件（参数为xml文件的路径）
                PortXmlDoc.Load(XmlFilePath);
                //获得第一个姓名匹配的节点（SelectSingleNode）：此xml文件的根节点
                XmlNode rootNode = PortXmlDoc.SelectSingleNode("ports");
                //获得该节点的子节点（即：该节点的第一层子节点）
                XmlNodeList portNodeList = rootNode.ChildNodes;
                string DeviceName = "";
                List<string> comList = new List<string>();
                foreach (XmlNode portNode in portNodeList)
                {
                    List<string> PortAddress = new List<string>();
                    //获得该节点的属性集合
                    XmlAttributeCollection attributeCol = portNode.Attributes;
                    foreach (XmlAttribute attri in attributeCol)
                    {
                        PortAddress.Add(attri.Value);
                        if (attri.Name == "name")
                        {
                            comList.Add(attri.Value);
                        }
                    }
                    //判断此节点是否还有子节点
                    if (portNode.HasChildNodes)
                    {
                        //获取该节点的第一个子节点
                        XmlNode deviceNode = portNode.FirstChild;
                        //获取该节点的值（即：端口对应的硬件）
                        DeviceName = deviceNode.Value.Trim();
                    }
                    //Debug.WriteLine(PortName + ":" + DeviceName);
                    //将设备与通信串口的关系写入全局变量
                    Global.Global.DeviceToPortDictionary.Add(DeviceName, PortAddress);
                }

                //检查硬件系统串口与软件系统串口设置是否一致
                ports = SerialPort.GetPortNames();
                if (ports.Length == 0)
                {
                    UIMessageDialog.ShowMessageDialog("系统没有检测到通信串口，启动失败，请联系系统管理员！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    //throw new Exception("No ports");
                }
                foreach (var pt in comList)
                {
                    if (!ports.Contains(pt.Trim()))
                    {
                        UIMessageDialog.ShowMessageDialog("没有检测到" + pt.Trim() + "通信串口，启动失败，请联系系统管理员！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        //throw new Exception("No ports");
                    }
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

        private static void InitializeEM()
        {
            string portName = Global.Global.DeviceToPortDictionary["EM3"][0];
            if (ports.Length == 0 || (!ports.Contains(portName.Trim())))
            {
                Global.Global.NEmPort = null;
                return;
            }
            else
            {
                //初始化PLC通信端口
                SerialPort emPort = new SerialPort();
                //串口名
                emPort.PortName = portName;
                //波特率
                emPort.BaudRate = 9600;
                //数据位
                emPort.DataBits = 8;
                //停止位
                emPort.StopBits = (StopBits)1;
                //校验位
                emPort.Parity = Parity.Even;
                //接收数据触发条件
                emPort.ReceivedBytesThreshold = 1;
                emPort.DtrEnable = true;
                if (!emPort.IsOpen)
                {
                    emPort.Open();
                }
                Global.Global.NEmPort = emPort;

                //Global.Global.NEMcomm = new EMcomm(Global.Global.NEmPort, "EM3");
                Global.Global.NEMcomm = new EMcomm(Global.Global.NEmPort, "EM3");
                Global.Global.NEMcomm.Timer.Start();
            }
        }

        private static void InitializePLC()
        {
            string portName = Global.Global.DeviceToPortDictionary["PLC"][0];
            if (ports.Length == 0 || (!ports.Contains(portName.Trim())))
            {
                Global.Global.PlcPort = null;
            }
            else
            {
                //初始化PLC1通信端口
                SerialPort plcPort = new SerialPort();
                //串口名
                plcPort.PortName = portName;
                //波特率
                plcPort.BaudRate = 9600;
                //数据位
                plcPort.DataBits = 8;
                //停止位
                plcPort.StopBits = (StopBits)1;
                //校验位
                plcPort.Parity = Parity.None;
                //接收数据触发条件
                plcPort.ReceivedBytesThreshold = 1;
                if (!plcPort.IsOpen)
                {
                    plcPort.Open();
                }
                Global.Global.PlcPort = plcPort;

                //初始化指示灯状态，将其设置为黄色。
                byte[] command = { 0x3A, 0x01, 0x01, 0x03 };
                command = CheckWorker.ADD(command,false);
                Global.Global.PlcPort.Write(command, 0, command.Length);
            }
            
        }

        /// <summary>
        /// 初始化温箱相关数据库记录
        /// </summary>
        private static void InitializeBox()
        {
            PtcBox box = new PtcBox();
            //查询ptc_box所有数据
            DataSet dataSet = DBHelper.GetDataSet(DBSql.SELECT_PTC_BOX, 1);

            box.ID = dataSet.Tables[0].Rows[0]["ID"].ToString();
            box.HighTemp = decimal.Parse(dataSet.Tables[0].Rows[0]["HighTemp"].ToString());
            box.LowTemp = decimal.Parse(dataSet.Tables[0].Rows[0]["LowTemp"].ToString());
            box.HighTime = decimal.Parse(dataSet.Tables[0].Rows[0]["HighTime"].ToString());
            box.LowTime = decimal.Parse(dataSet.Tables[0].Rows[0]["LowTime"].ToString());
            box.IsLineContrl = dataSet.Tables[0].Rows[0]["IsLineContrl"].ToString();
            box.XieLv = decimal.Parse(dataSet.Tables[0].Rows[0]["XieLv"].ToString());
            box.TestCycs = decimal.Parse(dataSet.Tables[0].Rows[0]["TestCycs"].ToString());
            box.StratPos = dataSet.Tables[0].Rows[0]["StratPos"].ToString();
            box.TempContrl = dataSet.Tables[0].Rows[0]["TempContrl"].ToString();
            box.BeforTemp = decimal.Parse(dataSet.Tables[0].Rows[0]["BeforTemp"].ToString());
            box.BeforTime = decimal.Parse(dataSet.Tables[0].Rows[0]["BeforTime"].ToString());
            box.AfterTemp = decimal.Parse(dataSet.Tables[0].Rows[0]["AfterTemp"].ToString());
            box.AfterTime = decimal.Parse(dataSet.Tables[0].Rows[0]["AfterTime"].ToString());
            box.Ysfz = dataSet.Tables[0].Rows[0]["Ysfz"].ToString();
            box.IsOpen = false;

            Global.Global.PtcBox = box;

            string portName = Global.Global.DeviceToPortDictionary["BOX"][0];
            if (ports.Length == 0 || (!ports.Contains(portName.Trim())))
            {
                Global.Global.BoxPort = null;
                return;
            }
            else
            {
                //初始化温箱通信端口
                SerialPort boxPort = new SerialPort();
                //串口名
                boxPort.PortName = portName;
                //波特率
                boxPort.BaudRate = 9600;
                //数据位
                boxPort.DataBits = 7;
                //停止位
                boxPort.StopBits = StopBits.One;
                //校验位
                boxPort.Parity = Parity.Even;

                boxPort.Handshake = Handshake.None;

                boxPort.RtsEnable = true;
                //接收数据触发条件
                boxPort.ReceivedBytesThreshold = 1;
                if (!boxPort.IsOpen)
                {
                    boxPort.Open();
                }
                Global.Global.BoxPort = boxPort;

                //关闭温箱
                string strCommand = "C1=OFF" + "\r\n";
                Global.Global.BoxPort.Write(strCommand);
            }
        }

        /// <summary>
        /// 初始化电源相关数据库记录
        /// </summary>
        private static void InitializePower()
        {
            //初始化电源通信串口
            SerialPort PowerPort;
            string portName;
            for (int i = 1; i <= 4; i++)
            {
                //初始化电源通信串口
                portName = Global.Global.DeviceToPortDictionary["Power" + i][0];
                if (ports.Length == 0 || (!ports.Contains(portName.Trim())))
                {
                    PowerPort = null;
                }
                else
                {
                    PowerPort = new SerialPort();
                    //串口名
                    PowerPort.PortName = portName;
                    //波特率
                    PowerPort.BaudRate = 9600;
                    //数据位
                    PowerPort.DataBits = 8;
                    //停止位
                    PowerPort.StopBits = (StopBits)1;
                    //校验位
                    PowerPort.Parity = Parity.None;

                    PowerPort.ReadTimeout = 150;

                    PowerPort.WriteTimeout = 150;

                    //接收数据触发条件
                    PowerPort.ReceivedBytesThreshold = 1;

                    if (!PowerPort.IsOpen)
                    {
                        PowerPort.Open();
                    }
                }
                Global.Global.LowPowerPortList.Add(PowerPort);
            }

            //初始化电源状态
            for (int i = 0; i < Global.Global.LowPowerPortList.Count; i++)
            {
                if (Global.Global.LowPowerPortList[i] != null)
                {
                    //获取远程控制权
                    Global.Global.LowPowerPortList[i].Write("ADR 1" + "\r\n");
                    Thread.Sleep(50);
                    //获取远程控制权
                    Global.Global.LowPowerPortList[i].Write("RMT 2" + "\r\n");
                    Thread.Sleep(50);
                    //设置初始电压为0
                    Global.Global.LowPowerPortList[i].Write("PV 0" + "\r\n");
                    Thread.Sleep(50);
                    //关闭电源输出
                    Global.Global.LowPowerPortList[i].Write("OUT 0" + "\r\n");
                }
            }

            //判断是否需要初始化
            object result = DBHelper.ExecuteScalar(DBSql.COUNT_HTRB_POWER, 1);
            int count = int.Parse(result.ToString());
            //如果需要初始化，则在数据库中建立电源记录。   
            if (count == 0)
            {
                //初始化电源记录
                for (int i = 1; i <= 4; i++)
                {
                    IdWorker idWorker = new IdWorker(1, 1);
                    string id = idWorker.NextId().ToString();
                    MySqlParameter[] paras = new MySqlParameter[] { new MySqlParameter("@ID", id), new MySqlParameter("@PowerName", "#" + i.ToString() + "号电源"), new MySqlParameter("@Voltage", "0") };
                    DBHelper.ExecuteNonQuery(DBSql.INSERT_HTRB_POWER, 1, paras);
                }
            }

            //查询htrb_power所有数据
            DataSet dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_POWER, 1);

            List<Power> powerList = new List<Power>();
            for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
            {
                Power power = new Power(i);
                power.ID = dataSet.Tables[0].Rows[i]["ID"].ToString();
                power.PowerName = dataSet.Tables[0].Rows[i]["PowerName"].ToString();
                power.Voltage = decimal.Parse(dataSet.Tables[0].Rows[i]["Voltage"].ToString());
                power.UpStep = decimal.Parse(dataSet.Tables[0].Rows[i]["UpStep"].ToString());
                power.UpInterval = decimal.Parse(dataSet.Tables[0].Rows[i]["UpInterval"].ToString());
                power.DownStep = decimal.Parse(dataSet.Tables[0].Rows[i]["DownStep"].ToString());
                power.DownInterval = decimal.Parse(dataSet.Tables[0].Rows[i]["DownInterval"].ToString());
                power.CheckInterval = decimal.Parse(dataSet.Tables[0].Rows[i]["CheckInterval"].ToString());
                power.BHDZ = decimal.Parse(dataSet.Tables[0].Rows[i]["BHDZ"].ToString());
                power.MaxVoltage = decimal.Parse(dataSet.Tables[0].Rows[i]["MaxVoltage"].ToString());
                power.MaxCurrent = decimal.Parse(dataSet.Tables[0].Rows[i]["MaxCurrent"].ToString());
                power.OnTime = decimal.Parse(dataSet.Tables[0].Rows[i]["OnTime"].ToString());
                power.OffTime = decimal.Parse(dataSet.Tables[0].Rows[i]["OffTime"].ToString());
                power.IsOpen = false;
                power.VoltageCurrent = 0;

                powerList.Add(power);
            }
            Global.Global.PowerList = powerList;

            Thread.Sleep(2000);
        }

        /// <summary>
        /// 初始化老化板相关数据库记录
        /// </summary>
        private static void InitializeChannel(bool isInit)
        {
            //判断是否需要初始化
            object result = DBHelper.ExecuteScalar(DBSql.COUNT_HTRB_CHANNEL, 1);
            int count = int.Parse(result.ToString());
            //如果需要初始化，则在数据库中建立老化板记录。   
            if (count == 0)
            {
                IdWorker idWorker = new IdWorker(1, 1);
                //8个老化板初始记录，初始状态，老化板的供电电源为未设置状态，PowerID赋值为null。
                string chid;
                for (int i = 1; i <= 8; i++)
                {
                    chid = idWorker.NextId().ToString();
                    string istr = i.ToString();
                    if (istr.Length == 1)
                    {
                        istr = "0" + istr;
                    }
                    MySqlParameter[] paras = new MySqlParameter[] { new MySqlParameter("@ID", chid), new MySqlParameter("@ChannelName", "#" + istr + "老化板"), new MySqlParameter("@PowerID", null) };
                    DBHelper.ExecuteNonQuery(DBSql.INSERT_HTRB_CHANNEL, 1, paras);

                    //初始化老化板工位记录
                    for (int j = 0; j < 4; j++)
                    {
                        string posid = idWorker.NextId().ToString();
                        paras = new MySqlParameter[] { new MySqlParameter("@ID", posid), new MySqlParameter("@ChID", chid), new MySqlParameter("@ChannelName", "#" + istr + "老化板"), new MySqlParameter("@PosIndex", j.ToString()), new MySqlParameter("@BasicValue", "0") };
                        DBHelper.ExecuteNonQuery(DBSql.INSERT_HTRB_CHANNEL_POSITIONS, 1, paras);
                    }

                }
            }
            //查询老化板记录
            DataSet dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_CHANNEL, 1);
            List<Channel> ChannelList = new List<Channel>();
            for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
            {
                Channel channel = new Channel(i);
                channel.ID = dataSet.Tables[0].Rows[i]["ID"].ToString();
                channel.ChannelName = dataSet.Tables[0].Rows[i]["ChannelName"].ToString();

                channel.BHDZ = decimal.Parse(dataSet.Tables[0].Rows[i]["BHDZ"].ToString());
                channel.CYDZ = decimal.Parse(dataSet.Tables[0].Rows[i]["CYDZ"].ToString());
                channel.DLYZ = decimal.Parse(dataSet.Tables[0].Rows[i]["DLYZ"].ToString());
                channel.ToInit = decimal.Parse(dataSet.Tables[0].Rows[i]["ToInit"].ToString());
                //3次拟合公式系数
                channel.X3XS = decimal.Parse(dataSet.Tables[0].Rows[i]["X3XS"].ToString(), System.Globalization.NumberStyles.Float);
                channel.X2XS = decimal.Parse(dataSet.Tables[0].Rows[i]["X2XS"].ToString(), System.Globalization.NumberStyles.Float);
                channel.X1XS = decimal.Parse(dataSet.Tables[0].Rows[i]["X1XS"].ToString(), System.Globalization.NumberStyles.Float);
                channel.X0XS = decimal.Parse(dataSet.Tables[0].Rows[i]["X0XS"].ToString(), System.Globalization.NumberStyles.Float);
                //参数校正项
                channel.GWJZ_K = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ_K"].ToString());
                channel.GWJZ_B = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ_B"].ToString());
                channel.GWJZ1_K = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ1_K"].ToString());
                channel.GWJZ1_B = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ1_B"].ToString());
                channel.GWJZ10_K = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ10_K"].ToString());
                channel.GWJZ10_B = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ10_B"].ToString());
                channel.GWJZ100_K = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ100_K"].ToString());
                channel.GWJZ100_B = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ100_B"].ToString());
                channel.GWJZ1000_K = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ1000_K"].ToString());
                channel.GWJZ1000_B = decimal.Parse(dataSet.Tables[0].Rows[i]["GWJZ1000_B"].ToString());

                //查询老化板工位记录
                MySqlParameter[] paras = new MySqlParameter[] { new MySqlParameter("@ChID", channel.ID) };
                DataSet dataSetPos = DBHelper.GetDataSet(DBSql.SELECT_HTRB_CHANNEL_POSITIONS, 1, paras);
                for (int j = 0; j < dataSetPos.Tables[0].Rows.Count; j++)
                {
                    for (int n = 0; n < channel.Positions.Count; n++)
                    {
                        Position position = channel.Positions[n];
                        if (position.Index == int.Parse(dataSetPos.Tables[0].Rows[j]["PosIndex"].ToString()))
                        {
                            position.ID = dataSetPos.Tables[0].Rows[j]["ID"].ToString();
                            position.ChID = dataSetPos.Tables[0].Rows[j]["ChID"].ToString();
                            position.ChannelName = dataSetPos.Tables[0].Rows[j]["ChannelName"].ToString();
                            position.Index = int.Parse(dataSetPos.Tables[0].Rows[j]["PosIndex"].ToString());
                            position.BasicValue = decimal.Parse(dataSetPos.Tables[0].Rows[j]["BasicValue"].ToString());

                            //参数校正项
                            position.GWJZ_K = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ_K"].ToString());
                            position.GWJZ_B = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ_B"].ToString());
                            position.GWJZ1_K = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ1_K"].ToString());
                            position.GWJZ1_B = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ1_B"].ToString());
                            position.GWJZ10_K = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ10_K"].ToString());
                            position.GWJZ10_B = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ10_B"].ToString());
                            position.GWJZ100_K = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ100_K"].ToString());
                            position.GWJZ100_B = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ100_B"].ToString());
                            position.GWJZ1000_K = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ1000_K"].ToString());
                            position.GWJZ1000_B = decimal.Parse(dataSetPos.Tables[0].Rows[j]["GWJZ1000_B"].ToString());

                            break;
                        }
                    }
                }

                //设置老化板电源组
                channel.PowerList = Global.Global.PowerList;

                //老化板测试参数方案置空 
                channel.TestParameter = null;

                ChannelList.Add(channel);
            }
            Global.Global.ChannelList = ChannelList;

            Global.Global.DataIRList = new List<decimal>(Global.Global.ChannelList.Count * Global.Global.ChannelList[0].Positions.Count);
            for (int i = 0; i < Global.Global.ChannelList.Count * Global.Global.ChannelList[0].Positions.Count; i++)
            {
                Global.Global.DataIRList.Add(0);
            }
            //插板检测标志
            for (int i = 0; i < Global.Global.ChannelList.Count; i++)
            {
                Global.Global.FlagButtons.Add(false);
            }

            //初始化老化板通信端口
            CommPort Port = null;
            if (ports.Length == 0 || (!ports.Contains(Global.Global.DeviceToPortDictionary["CHANNEL"][0])))
            {
                Global.Global.ChannelPort = Port;
            }
            else
            {
                Port = new CommPort();
                //串口名
                Port.PortName = Global.Global.DeviceToPortDictionary["CHANNEL".ToString()][0];
                //波特率
                Port.BaudRate = 38400;
                //数据位
                Port.ByteSize = 8;
                //停止位
                Port.StopBits = 0;
                //校验位
                Port.Parity = 3;

                Port.ReadTimeout = 20;

                if (!Port.Opened)
                {
                    Port.Open();
                }
            }
            Global.Global.ChannelPort = Port;

            //停止运行
            byte[] commandRun = { 0xAA, 0xB0, 0x01, 0x00, 0x00 };
            commandRun = CheckWorker.ADD(commandRun, true);
            Global.Global.ChannelPort.Write(commandRun);
            Thread.Sleep(50);
            //继电器开合
            byte[] mmd = { 0xAA, 0xB0, 0x06, 0x00, 0x00 };
            mmd = CheckWorker.ADD(mmd, true);
            Global.Global.ChannelPort.Write(mmd);
            Thread.Sleep(1000);

            /*Channel channelTemp = new Channel(3);
            channelTemp.BHDZ = decimal.Parse(dataSet.Tables[0].Rows[0]["BHDZ"].ToString());//保护电阻
            channelTemp.CYDZ = decimal.Parse(dataSet.Tables[0].Rows[0]["CYDZ"].ToString());//采样电阻
            channelTemp.DLYZ = decimal.Parse(dataSet.Tables[0].Rows[0]["DLYZ"].ToString());//短路报警阈值

            Global.Global.PowerChannel = channelTemp;*/

            //开启电源检测板.
            /*commandRun = new byte[] { 0xAA, 0xB0, 0x05, 0x00, 0x00 };
            commandRun = CheckWorker.ADD(commandRun);
            Global.Global.ChannelPort.Write(commandRun);
            Thread.Sleep(60);
            commandRun = new byte[] { 0xAA, 0xB0, 0x02, 0x00, 0x00 };
            commandRun = CheckWorker.ADD(commandRun);
            Global.Global.ChannelPort.Write(commandRun);*/

            //初始化IR基础值
            /*if (isInit)
            {
                AutoRun.setBasicValue();
            }*/
        }

        private static void InitializeBasicData()
        {
            //开启电源检测板.
            byte[] commandRun = new byte[] { 0xAA, 0xB0, 0x06, 0x00, 0x00 };
            commandRun = CheckWorker.ADD(commandRun, true);
            Global.Global.ChannelPort.Write(commandRun);
            Thread.Sleep(60);
            commandRun = new byte[] { 0xAA, 0xB0, 0x02, 0x00, 0x00 };
            commandRun = CheckWorker.ADD(commandRun, true);
            Global.Global.ChannelPort.Write(commandRun);

            Thread.Sleep(4000);

            byte[] Command = CheckWorker.ADD(new byte[] { 0xAA, 0xB0, 0x04, 0x00, 0x28 }, true);
            Global.Global.ChannelPort.Read(Global.Global.ChannelPort.GetNumToRead());
            Global.Global.ChannelPort.Write(Command);
            //Thread.Sleep(100);
            for (int i = 0; i < 5; i++)
            {
                System.Threading.Thread.Sleep(25);
                if (Global.Global.ChannelPort.GetNumToRead() == 165)
                {
                    break;
                }
            }

            byte[] DataBuffer = Global.Global.ChannelPort.Read(165);
            if (DataBuffer.Length == 0 || DataBuffer.Length != 165)
            {
                return;
            }

            byte[] ReceiveBytes = DataBuffer;

            string returnStr = "";
            for (int i = 0; i < ReceiveBytes.Length; i++)
            {
                returnStr += ReceiveBytes[i].ToString("X2") + "  ";
            }
            Debug.WriteLine("计算基础值接收的全部数据：" + ReceiveBytes.Length + "-->" + returnStr);

            byte[] data = new byte[ReceiveBytes.Length - 5];
            for (int i = 4; i < ReceiveBytes.Length - 1; i++)
            {
                data[i - 4] = ReceiveBytes[i];
            }

            //数据解析
            int start = 0;
            for (int i = 0; i < Global.Global.DataIRList.Count; i++)
            {
                int chIndex = i / Global.Global.ChannelList[0].Positions.Count;
                int pIndex = i % Global.Global.ChannelList[0].Positions.Count;

                decimal num = 1000;
                byte bFlag = data[start + 1];
                string strFlag = bFlag.ToString("X2");
                if (strFlag == "00")
                {
                    num = 1000;
                }
                else if (strFlag == "01")
                {
                    num = 100;
                }
                else if (strFlag == "02")
                {
                    num = 10;
                }
                else if (strFlag == "03")
                {
                    num = 1;
                }
                byte bOne = data[start + 2];
                byte btow = data[start + 3];
                byte[] bb = { bOne, btow };
                string bbStr = "";
                for (int n = 0; n < bb.Length; n++)
                {
                    bbStr += bb[n].ToString("X2");
                }
                short intValue = Convert.ToInt16(bbStr, 16);
                decimal dataValue = decimal.Parse(intValue.ToString());
                decimal num2_5 = 2.5m;
                decimal num32768 = 32768;
                //IR(A)
                decimal IR;
                IR = dataValue / num * num2_5 / num32768 / Global.Global.ChannelList[0].CYDZ;
                Debug.WriteLine("电流" + (i + 1) + "的基础值(mA)：" + IR * 1000);

                Global.Global.ChannelList[chIndex].Positions[pIndex].BasicValue = Math.Round(IR * 1000, 3);

                start = start + 4;
            }

        }

    }

}

